package org.lgy.sso_server.filter;


import cn.hutool.core.util.StrUtil;
import org.lgy.sso_comment.constant.AuthConst;
import org.lgy.sso_server.storage.ClientStorage;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * sso认证中心会话过滤
 */
@WebFilter(filterName = "SessionFilter", urlPatterns = "/*")
public class SessionFilter implements Filter {

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		String uri = request.getRequestURI().replace(request.getContextPath(), "");

		// 注销请求，放行
		if ("/logout".equals(uri)) {
			chain.doFilter(req, res);
			return;
		}
		if ("/tokenCheck".equals(uri)) {
			chain.doFilter(req, res);
			return;
		}
		
		// 已经登录，放行
		Boolean isLogin = (Boolean) session.getAttribute(AuthConst.IS_LOGIN);
		if (isLogin != null && isLogin) {
			// 如果是客户端发起的登录请求，跳转回客户端，并附带token
			String token = (String) session.getAttribute(AuthConst.TOKEN);
			String clientUrl = request.getParameter(AuthConst.CLIENT_URL);
			if (StrUtil.isNotBlank(clientUrl)) {
				// 存储，用于注销
				ClientStorage.INSTANCE.set(token, clientUrl);
				response.sendRedirect(clientUrl + "?" + AuthConst.TOKEN + "=" + token);
				return;
			}

			if (!"/success".equals(uri)) {
				response.sendRedirect(request.getContextPath() + "/success");
				return;
			}
			chain.doFilter(req, res);
			return;
		}
		// 登录请求，放行
		if ("/".equals(uri) || "/login".equals(uri)) {
			chain.doFilter(req, res);
			return;
		}

		// 其他请求，拦截
		response.sendRedirect("/");
	}

	@Override
	public void init(FilterConfig config) throws ServletException {}
}